﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using RRRSRoguelike.Entities;
using RRRSRoguelike.Managers;

namespace RRRSRoguelike.Helpers.Behaviors
{
    public class Mindless
    {
        public static void MoveToTarget(Monster caller,Point target)
        {
            Point temp = caller.Position;
            IList<Monster> Monsters = DungeonManager.Instance.CreatureManager.Monsters;
			caller.hasMoved = false;

            //move on x axis toward player
            if (caller.X != target.X)
                temp.X += (caller.X > target.X) ? -1 : 1;
            //move on y axis toward player
            if (caller.Y != target.Y)
                temp.Y += (caller.Y > target.Y) ? -1 : 1;

            DungeonLevel.ClampToDungeon(temp);

            // m stands for Monster in monsters. Prevents monsters from stacking(moving onto the same square).
            if (DungeonManager.Instance.DungeonLevel.IsOKToMove(temp) &&
            		!Monsters.Any(m => m.X == temp.X && m.Y == temp.Y))
            {
                caller.hasMoved = true;
                caller.Position = temp;
            }
            else if (DungeonManager.Instance.DungeonLevel.IsOKToMove(new Point(temp.X,caller.Position.Y)) &&
            	!Monsters.Any(m => m.X == temp.X && m.Y == caller.Position.Y))
            {
                //this resets the temp move to the orginal position resulting in no move on the y axis
                temp.Y = caller.Position.Y;
                caller.hasMoved = true;
                caller.Position = temp;
            }
            else if (DungeonManager.Instance.DungeonLevel.IsOKToMove(new Point(caller.Position.X,temp.Y)) &&
                     !Monsters.Any(m => m.X == caller.Position.X && m.Y == temp.Y))
            {
                //this resets the temp move to the orginal position resulting in no move on the x axis
                temp.X = caller.Position.X;
                caller.hasMoved = true;
                caller.Position = temp;
            }
            	//if blocking monster won't move or temp is where we are standing then give up
            else if (Monsters.Where(m => m.Position == temp).Count() > 0 &&
            	    Monsters.Where(m => m.Position == temp).FirstOrDefault().hasMoved)
            		caller.hasMoved	 = true;
            	
            else if (caller.X == temp.X && caller.Y == temp.Y)
                    caller.hasMoved = true;
            
            else if (Monsters.Where(m => m.Position == temp).Count() > 0 &&
            	    !Monsters.Where(m => m.Position == temp).FirstOrDefault().hasMoved)
            {
            	caller.hasMoved = false;
            }
            else
            	caller.hasMoved = true;
            }
        }
    }
